package admin

import (
	"exercise/application/yiran/app/libs"
	"exercise/application/yiran/app/model"
	"exercise/application/yiran/app/request/adminRequest"
	"fmt"
	"github.com/gin-gonic/gin"
)

type jzwService struct{}

func (*jzwService) List(ctx *gin.Context, request *adminRequest.JzwListRequest) (map[string]interface{}, error) {
	schoolId, _ := ctx.Get("schoolId")
	list := make([]model.Jzw, 0)
	pageing := model.Paging{}
	pageing.Page = request.Page
	pageing.PageSize = request.PageSize

	total, err := model.NewDb("").FindAllAndCount(&list, "school_id = ? AND jzw_name LIKE ?", []interface{}{schoolId, "%" + request.Keyword + "%"}, model.OrderOrGroup{}, pageing, []string{})

	if err != nil {
		return nil, fmt.Errorf("暂无数据：%w", err)
	}

	return map[string]interface{}{
		"list":  list,
		"total": total,
	}, err
}

func (*jzwService) Add(ctx *gin.Context, request *adminRequest.AddJzwRequest) (id int64, err error) {

	schoolId, _ := ctx.Get("schoolId")
	jzw := new(model.Jzw)

	jzw.JzwName = request.JzwName
	jzw.Address = request.Address
	jzw.SchoolId = schoolId.(int64)
	jzw.CreateTime = libs.CurrentTime()

	err = model.NewDb("").InsertRecord(jzw)
	if err != nil {
		return id, err
	}

	return jzw.Id, nil
}

func (*jzwService) Edit(request *adminRequest.EditJzwRequest) error {

	jzw := new(model.Jzw)
	err := model.NewDb("").FindOne(jzw, "id = ? ", []interface{}{request.Id}, "*", []string{})
	if err != nil {
		return err
	}
	jzw.JzwName = request.JzwName
	jzw.Address = request.Address

	err = model.NewDb("").SaveRecord(jzw)
	if err != nil {
		return err
	}
	return nil
}

func (*jzwService) Detail(ctx *gin.Context) (res interface{}, err error) {
	id := ctx.Param("id")
	jzw := new(model.Jzw)
	err = model.NewDb("").FindOne(jzw, "id = ? ", []interface{}{id}, "*", []string{})
	if err != nil {
		return nil, fmt.Errorf("数据异常：%w", err)
	}
	return jzw, err
}

func (*jzwService) Deleted(ctx *gin.Context) error {
	id := ctx.Param("id")
	jzw := new(model.Jzw)
	err := model.NewDb("").DeleteRecord(jzw, "id = ?", []interface{}{id})
	return err
}

func NewJzwService() *jzwService {
	return &jzwService{}
}
